import cv2
import numpy as np

# ---------------- 可调参数 ----------------
IMG_PATH   = r'../img/new/0006.tif'  # 你的图
MAX_DISP_H = 600                    # 窗口最大高度（像素）
WIN_SHAPE  = (300, 300)             # 滑动窗口大小（原图尺度）
STEP       = 40                     # 滑动步长（原图尺度）

# ---------------- 工具函数 ----------------
def auto_roi(gray, win_shape, step):
    h, w = gray.shape
    wh, ww = win_shape
    best, best_xy = -1, (0, 0)
    for y in range(0, h-wh+1, step):
        for x in range(0, w-ww+1, step):
            patch = gray[y:y+wh, x:x+ww]
            f = np.fft.fft2(patch)
            mag = np.abs(np.fft.fftshift(f))
            cy, cx = wh//2, ww//2
            Y, X = np.ogrid[:wh, :ww]
            dist = np.sqrt((X-cx)**2 + (Y-cy)**2)
            mask = (dist>10) & (dist<min(cx,cy)*0.4)
            score = np.sum(mag[mask])
            if score>best: best, best_xy = score, (x,y)
    x,y = best_xy
    return x, y, ww, wh

# ---------------- 主流程 ----------------
gray = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
assert gray is not None, "图像读取失败"

h0, w0 = gray.shape
scale = min(1.0, MAX_DISP_H / h0)           # 缩放比例
h1, w1 = int(h0*scale), int(w0*scale)

# 1. 自动 ROI（原图坐标）
x, y, w, h = auto_roi(gray, WIN_SHAPE, STEP)

# 2. 缩小显示
small = cv2.resize(gray, (w1, h1), interpolation=cv2.INTER_AREA)
vis   = cv2.cvtColor(small, cv2.COLOR_GRAY2BGR)
xs, ys, ws, hs = int(x*scale), int(y*scale), int(w*scale), int(h*scale)
cv2.rectangle(vis, (xs, ys), (xs+ws, ys+hs), (0,0,255), 2)
cv2.imshow('Preview (press q to accept / any other to adjust)', vis)
print('自动 ROI（原图）:', x, y, w, h)

if cv2.waitKey(0) & 0xFF == ord('q'):
    final = (x, y, w, h)
else:
    cv2.destroyAllWindows()
    # 终端微调（原图坐标）
    print("输入微调值（直接回车保持原值）:")
    x = int(input(f"x({x}): ") or x)
    y = int(input(f"y({y}): ") or y)
    w = int(input(f"w({w}): ") or w)
    h = int(input(f"h({h}): ") or h)
    final = (x, y, w, h)

cv2.destroyAllWindows()
roi = gray[final[1]:final[1]+final[3], final[0]:final[0]+final[2]]
print("最终 ROI（原图坐标）:", final)
cv2.imshow('Selected ROI', roi)
cv2.waitKey(0)
cv2.destroyAllWindows()